package com.ivan.toolkit.swing;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;

import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class PromptPswdField extends JPasswordField implements DocumentListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 2765605130177898140L;
	
	/**
	 * Label to show when no text
	 */
	private JLabel nullLabel = null;
	
	/**
	 * 
	 */
	private boolean verified = true;
	

	public PromptPswdField() {
		super();
	}
	
	/**
	 * Get label showed when no text inputed
	 */
	public JLabel getNullLabel() {
		if(this.nullLabel == null) {
			this.nullLabel = new JLabel();
			this.nullLabel.setForeground(Color.LIGHT_GRAY);
		}
		return this.nullLabel;
	}

	/**
	 * check inputed text is valid
	 */
	public boolean isVerified() {
		return this.verified;
	}

	@Override
	protected void paintComponent(Graphics g) {
		
		// draw default
		super.paintComponent(g);
		
		if(this.getPassword().length == 0 && !this.isFocusOwner()) {
			Insets insets = this.getInsets();
			SwingUtilities.paintComponent(
					g, 
					getNullLabel(), 
					this, 
					insets.left, 
					insets.top,
					this.getWidth() - insets.left - insets.right, 
					this.getHeight() - insets.top - insets.bottom);	
		}
		
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		doVerify();
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		doVerify();
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		doVerify();
	}
	
	/**
	 * Internal verify logic
	 */
	private void doVerify() {
		
		boolean v;
		
		if(this.getPassword().length == 0) {
			v = true;
		} else {
			v = verify();
		}
		
		if(v != verified) {
			verified = v;
			onVerifyChanged();
		}
		
	}
	
	/**
	 * verify function to be override 
	 */
	protected boolean verify() {
		return true;
	}
	
	/**
	 * called when verify state changed
	 */
	protected void onVerifyChanged() {
		if(this.isVerified()) {
			this.setBackground(Color.WHITE);
		} else {
			this.setBackground(new Color(255, 224, 224));
		}
	}
	


}
